<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            检测单列表
        </div>
    </header>

    <div id="divhtml" style="width:100%;overflow: hidden; margin-top:50px;">

        <!-- <div style="width: 100%;margin-top:1%;border:solid 1px #D3D3D3;overflow: hidden;">
            <div>
                <span style="font-size:18px;">检测项11124214124214214212</span>
            </div>
            <div class="aui-list-item-input" style="width:100%;font-size:18px;">
                <label><input style="margin-top:10px; margin-bottom:1px;" type="radio"  id ="inType" value="IN" name="type" checked> OK</label>
                <label><input style="margin-top:10px; margin-bottom:1px;" type="radio"  id ="outType" value="OUT" name="type"> NG</label>
            </div>
            <div class="aui-content" style="background-color: #ffffff">
                <ul class="aui-list-view aui-grid-view" id="imgslist">
                    <li class="aui-list-view-cell aui-img aui-col-xs-4" id="addpic" onclick="imgClick()">
                        <img class="aui-img-object" src="../image/add.jpg">
                    </li>
                </ul>
            </div>
        </div> -->

    </div>
    <div class="aui-content aui-content-padded" style="text-align:center;margin-bottom: 5%">
        <p>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="save()">保存</div>
        </p>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/doT.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript">

    var uiMediaScanner = null;
    var imageFilter = null;
    var imageBrowser = null;
    var billCode = null;
    var mrlCode = null;
    var chkList = [];
    var actualQty = null;
    apiready = function () {
        //src = "http://localhost:8080/htsys/app/getChkImage/ST3线和SA4线减振器总成和分总成清洁度检测_1700378929000.jpg"
        //$('#cc').attr('src','http://localhost:8084/htsys/md/mdfileinfo/getChkImage/wmcustomermrl');
        //$('#cc').attr('src','/app/getChkImage/ST3线和SA4线减振器总成和分总成清洁度检测_1700378929000.jpg');
        // 引入多选模块
        uiMediaScanner = api.require('UIMediaScanner');
        // 引入过滤压缩模块
        imageFilter = api.require("imageFilter");
        // 引入图片浏览模块
        imageBrowser = api.require('imageBrowser');

        billCode = api.pageParam.chkBillCode;
        actualQty = api.pageParam.actualQty;
        mrlCode = api.pageParam.mrlCode;
        document.getElementById("title").innerHTML = '抽检物料' + mrlCode + '处理';
        doSearch();
    };

    //查询检测单
    function doSearch() {

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getChkBill_citem";
        var data = {
            values: {
                billCode: billCode,
                appVersion: api.appVersion,
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    var list = eval(myobj.list);
                    chkList = list;
                    var html = "";
                    for (var i = 0; i < list.length; i++) {
                        //序号
                        html += "<div style='width: 100%;margin-top:1%;border:solid 1px #D3D3D3;overflow: hidden;'>";
                        html += "<div> <span style='font-size:18px;'>" + list[i].name + "</span> </div>";
                        html += "<div class='aui-list-item-input' style='width:100%;font-size:18px;'>";
                        html += "<label><input style='margin-top:10px; margin-bottom:1px;' type='radio'  id ='" + list[i].code + 'ok' + "' value='OK' name='" + list[i].code + 'type' + "'";
                        if(list[i].result == null || list[i].result == "" || list[i].result == undefined || list[i].result == '7'){
                            html += " checked ";
                        }
                        html += "> OK</label>";
                        html += "<label><input style='margin-top:10px; margin-bottom:1px;' type='radio'  id ='" + list[i].code + 'ng' + "' value='NG' name='" + list[i].code + 'type' + "' ";
                        if(list[i].result == '1'){
                            html += " checked ";
                        }
                        html += "> NG</label>";
                        html += "</div>";
                        html += "<div class='aui-content' style='background-color: #ffffff'>";
                        html += "<ul class='aui-list-view aui-grid-view' id='" + list[i].code + 'imgslist' + "'>";
                        
                        if(list[i].imgListSize != '0'){
                            for(var x = 0;x < parseInt(list[i].imgListSize); x++){
                                var imgPath = serverUrl + '/md/mdfileinfo/getChkImage/' + list[i].name + ',' + billCode + ',' + x;
                                html +=   "<li class='aui-list-view-cell aui-img aui-col-xs-4' onclick='lookImg(\"" + imgPath + "\")'><img class='aui-img-object' src='" + imgPath +
                                            "' style='width:150px;height:150px;'></li>";
                            }
                        }

                        html += "<li class='aui-list-view-cell aui-img aui-col-xs-4' id='" + list[i].code + 'addpic' + "' onclick='imgClick(\"" + list[i].code + "\",\"" + list[i].name + "\")'>";
                        html += "<img class='aui-img-object' src='../image/add.jpg'>";
                        html += "</li> </ul></div></div>";
                    }
                    $api.html($api.byId("divhtml"), html);
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }

    //选则返回函数
    function setChkBill(id, code, mrlCode, mrlName, opCode, opName, chkTypeName, supplierName, lotCode, actualQty, cjqty, isTightened, tightenedEndDate, ext07_k) {
        api.closeWin();
        var name = api.pageParam.name;

        if (isTightened == 'Y') {
            isTightened = '是';
        } else {
            isTightened = '否';
        }
        api.execScript({
            name: name,
            script: 'setChkBill("' + id + '","' + code + '","' + mrlCode + '","' + mrlName + '","' + opCode + '","' + opName + '","' + chkTypeName + '","' + supplierName + '","' + lotCode + '","' + actualQty + '","' + cjqty + '","' + isTightened + '","' + tightenedEndDate + '","' + ext07_k + '")'
        });
    }

    //返回按钮
    function closeWin() {
        api.closeWin({});
    }

    function imgClick(code, name) {
        // 获取图片宽高
        var normalW = $("#" + code + "addpic img").width();

        api.actionSheet({
            title: '选择图片来源',
            buttons: ['照相机', '浏览相册']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            switch (index) {
                // 拍照
                case 1:
                    // 打开拍照
                    api.getPicture({
                        sourceType: "camera",
                        encodingType: "jpg",
                        destinationType: "url",
                        mediaValue: "pic",
                        quality: 50,
                        saveToPhotoAlbum: true
                    }, function (ret, err) {
                        if (ret && ret.data) {
                            // 拍照返回的本地路径
                            var returnUrl = ret.data;
                            // 图片压缩
                            imgCompress(name, returnUrl, 0.5, 0.5, getExt(returnUrl), function (compressImg) {
                                var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                    "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                // 追加图片
                                $("#" + code + "addpic").before(showImgHtml);
                                // ########################################  绑定长按事件 ########################
                                addPress($("#" + code + "imgslist img[src='" + compressImg + "']").parent("li"));

                                //上传图片
                                uploadFile(compressImg);
                            });
                        } else {
                            api.toast({
                                msg: '没有选择，或者选择出错'
                            });
                        }
                    });
                    break;
                // 打开图片选择器
                case 2:
                    uiMediaScanner.open({
                        type: 'picture',
                        column: 4,
                        classify: true,
                        max: 5,
                        sort: {
                            key: 'time',
                            order: 'desc'
                        },
                        texts: {
                            stateText: '已选*项',
                            cancelText: '取消',
                            finishText: '完成'
                        },
                        styles: {
                            bg: '#fff',
                            mark: {
                                icon: '',
                                position: 'bottom_left',
                                size: 20
                            },
                            nav: {
                                bg: '#b23e4b',
                                stateColor: '#fff',
                                stateSize: 18,
                                cancelBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 18,
                                finishBg: 'rgba(0,0,0,0)',
                                finishColor: '#fff',
                                finishSize: 18
                            }
                        }
                    }, function (ret) {
                        if (ret) {
                            for (var i = 0; i < ret.list.length; i++) {
                                var selectImg = ret.list[i];
                                // 获取图片的路径
                                var selectimgPath = selectImg.path;
                                var selectimgThumbPath = selectImg.thumbPath;
                                // 图片压缩
                                imgCompress(name, selectimgPath, 0.5, 0.5, selectImg.suffix, function (compressImg) {
                                    var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                        "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                    // 追加图片
                                    $("#" + code + "addpic").before(showImgHtml);
                                    // ########################################  绑定长按事件 ########################
                                    addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                    // ################### 上传图片 #########################
                                    uploadFile(compressImg);
                                });
                            }
                        }
                    });
                    break;
            }
        });
    }

    // 为图片添加点击预览功能,排除添加按钮
    function lookImg(compressImg) {
        // 定义一个数组，存储需要预览的图片
        var browerImgs = [];
        // 调用图片预览函数
        browerImgs.push(compressImg);
        openImageBrowser(browerImgs);
    }

    // 图片压缩
    // imgsrc：源图片的路径
    // quality：图片压缩质量，一般建议0.5
    // scale：图片压缩比例，也是建议0.5
    // ext：源图片拓展名
    // callback：转换成功之后回调函数
    function imgCompress(name, imgsrc, quality, scale, ext, callback) {
        // 压缩文件的保存目录
        var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
        // 压缩文件生成的随机文件名称
        var savename = NewGuid(name) + "." + ext;
        imageFilter.compress({
            img: imgsrc,
            quality: quality,
            scale: quality,
            save: {
                album: false,
                imgPath: savePath,
                imgName: savename
            }
        }, function (ret, err) {
            if (ret) {
                callback(savePath + savename);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 打开图片浏览
    // imgs：需要预览的图片集合
    function openImageBrowser(imgs) {
        imageBrowser.openImages({
            imageUrls: imgs,
            showList: false,
            activeIndex: 0
        });
    }

    // 添加长按方法
    function addPress(obj, index) {
        // 获取目前长按的对象
        var hammertime = new Hammer(obj[0]);
        // 绑定长按对象
        hammertime.on("press", function (e) {
            api.confirm({
                title: '温馨提示',
                msg: '您确定要删除该图片吗？',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    // 移除自己
                    $(obj).remove();
                    api.toast({
                        msg: '删除成功！'
                    });
                }
            });
        });
    }

    // 上传图片
    // url：上传的url地址
    // data：上传的文件
    // callback：上传成功返回地址
    function uploadFile(data) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/uploadPhotosAPP";
        var data = {
            values: {
                appVersion: api.appVersion,
                un: un
            },
            files: {
                file: data
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    console.log("上传成功");
                } else if (myobj.code == "1") {
                    alert("上传失败");
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
        return currentdate;
    }

    // 获取文件拓展名
    function getExt(fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    // 生成guid,主要用于生成随机文件名
    function NewGuid(name) {
        // function S4() {
        //     return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        // }

        return (name + '_' + Date.parse(new Date()));
    }


    function save() {
        var result = [];
        for (var x = 0; x < chkList.length; x++) {
            //操作类型
            var type = $("input[name='" + chkList[x].code + "type']:checked").val();
            result[x] = ({ code: chkList[x].code, name: chkList[x].name, type: type })
        }

        //获取imgslist中所有的img，保存图片和异常业务记录的关系
        var imgs = document.getElementsByTagName('img');
        var names = [];

        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            //alert(nameStr);
            if ("add.jpg" != nameStr) {
                names[i] = nameStr;
            }
        }

        var picNames = JSON.parse(JSON.stringify(names));
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/chkBillCitemSave";
        var data = {
            values: {
                result: result,
                appVersion: api.appVersion,
                chkCode: billCode,
                actualQty: actualQty,
                picNames: picNames,
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    alert("保存成功");
                    if (myobj.circumstance === true) {
                        var name = api.pageParam.name;
                        api.closeWin();
                        api.execScript({
                            name: name,
                            script: "setChkBillState('" + myobj.processState + "')"
                        });
                    } else {
                        api.closeWin();
                    }

                } else if (myobj.code == "1") {
                    alert("保存失败" + myobj.message);
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }


</script>

</html>